package org.goodsmanager.service;

import cn.hutool.core.lang.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.goodsmanager.entity.Product;
import org.goodsmanager.mapper.ProductMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品Service实现类
 *
 * @author Goods Manager System
 * @version 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductService {

    private final ProductMapper productMapper;

    /**
     * 添加商品
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"products", "productList"}, allEntries = true)
    public boolean addProduct(Product product) {
        try {
            // 检查商品编码是否已存在
            if (productMapper.checkCodeExists(product.getProductCode(), null) > 0) {
                log.warn("商品编码已存在: {}", product.getProductCode());
                return false;
            }

            // 生成UUID作为主键
            product.setId(UUID.randomUUID().toString());

            // 设置默认值
            if (product.getStockQuantity() == null) {
                product.setStockQuantity(0);
            }
            if (product.getMinStock() == null) {
                product.setMinStock(10);
            }
            if (product.getMaxStock() == null) {
                product.setMaxStock(1000);
            }
            if (product.getStatus() == null) {
                product.setStatus(1);
            }
            if (product.getIsHot() == null) {
                product.setIsHot(0);
            }
            if (product.getIsNew() == null) {
                product.setIsNew(0);
            }

            int result = productMapper.insert(product);
            log.info("添加商品成功: {}", product.getProductName());
            return result > 0;
        } catch (Exception e) {
            log.error("添加商品失败", e);
            throw new RuntimeException("添加商品失败: " + e.getMessage());
        }
    }

    /**
     * 更新商品
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"products", "productList"}, allEntries = true)
    public boolean updateProduct(Product product) {
        try {
            // 检查商品是否存在
            Product existProduct = productMapper.selectById(product.getId());
            if (existProduct == null) {
                log.warn("商品不存在: {}", product.getId());
                return false;
            }

            // 检查商品编码是否重复
            if (productMapper.checkCodeExists(product.getProductCode(), product.getId()) > 0) {
                log.warn("商品编码已被其他商品使用: {}", product.getProductCode());
                return false;
            }

            int result = productMapper.update(product);
            log.info("更新商品成功: {}", product.getProductName());
            return result > 0;
        } catch (Exception e) {
            log.error("更新商品失败", e);
            throw new RuntimeException("更新商品失败: " + e.getMessage());
        }
    }

    /**
     * 删除商品
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProduct(String id) {
        try {
            int result = productMapper.deleteById(id);
            log.info("删除商品成功, ID: {}", id);
            return result > 0;
        } catch (Exception e) {
            log.error("删除商品失败", e);
            throw new RuntimeException("删除商品失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除商品
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteProducts(List<String> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return false;
            }
            int result = productMapper.batchDelete(ids);
            log.info("批量删除商品成功, 删除数量: {}", result);
            return result > 0;
        } catch (Exception e) {
            log.error("批量删除商品失败", e);
            throw new RuntimeException("批量删除商品失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询商品
     */

    public Product getProductById(String id) {
        try {
            Product product = productMapper.selectById(id);
            if (product != null) {
                // 增加浏览次数
                productMapper.increaseViewCount(id);
            }
            return product;
        } catch (Exception e) {
            log.error("查询商品失败", e);
            throw new RuntimeException("查询商品失败: " + e.getMessage());
        }
    }

    /**
     * 查询所有商品
     */
    public List<Product> getAllProducts() {
        try {
            return productMapper.selectAll();
        } catch (Exception e) {
            log.error("查询所有商品失败", e);
            throw new RuntimeException("查询所有商品失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询商品
     */
    public Map<String, Object> getProductsByPage(int currentPage, int pageSize,
                                                 String keyword, String categoryId,
                                                 Integer status, Double minPrice, Double maxPrice,
                                                 String sortBy, String sortOrder) {
        try {
            // 计算偏移量
            int offset = (currentPage - 1) * pageSize;

            // 查询数据
            List<Product> products = productMapper.selectByPage(offset, pageSize,
                    keyword, categoryId, status, minPrice, maxPrice, sortBy, sortOrder);

            // 处理可能的循环引用问题
            for (Product product : products) {
                // 清除可能引起循环引用的属性
                if (product.getCategoryName() != null) {
                    // 确保categoryName只是一个简单的字符串，不包含Category对象
                    // 这样可以避免循环引用
                }
            }

            // 查询总数
            int total = productMapper.countAll(keyword, categoryId, status, minPrice, maxPrice);

            // 计算总页数
            int totalPages = (int) Math.ceil((double) total / pageSize);

            // 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("records", products); // 修改为records以匹配前端模板
            result.put("currentPage", currentPage);
            result.put("pageSize", pageSize);
            result.put("total", total);
            result.put("totalPages", totalPages);

            return result;
        } catch (Exception e) {
            log.error("分页查询商品失败", e);
            throw new RuntimeException("分页查询商品失败: " + e.getMessage());
        }
    }

    /**
     * 搜索商品
     */
    public Map<String, Object> searchProducts(String keyword, int currentPage, int pageSize) {
        try {
            int offset = (currentPage - 1) * pageSize;
            List<Product> products = productMapper.searchProducts(keyword, offset, pageSize);
            int total = productMapper.countSearchResults(keyword);
            int totalPages = (int) Math.ceil((double) total / pageSize);

            Map<String, Object> result = new HashMap<>();
            result.put("products", products);
            result.put("currentPage", currentPage);
            result.put("pageSize", pageSize);
            result.put("total", total);
            result.put("totalPages", totalPages);
            result.put("keyword", keyword);

            return result;
        } catch (Exception e) {
            log.error("搜索商品失败", e);
            throw new RuntimeException("搜索商品失败: " + e.getMessage());
        }
    }

    /**
     * 更新库存
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStock(String id, int quantity) {
        try {
            int result = productMapper.updateStock(id, quantity);
            log.info("更新库存成功, ID: {}, 变化量: {}", id, quantity);
            return result > 0;
        } catch (Exception e) {
            log.error("更新库存失败", e);
            throw new RuntimeException("更新库存失败: " + e.getMessage());
        }
    }

    /**
     * 批量更新状态
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateStatus(List<String> ids, Integer status) {
        try {
            if (ids == null || ids.isEmpty()) {
                return false;
            }
            int result = productMapper.batchUpdateStatus(ids, status);
            log.info("批量更新状态成功, 更新数量: {}", result);
            return result > 0;
        } catch (Exception e) {
            log.error("批量更新状态失败", e);
            throw new RuntimeException("批量更新状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取热销商品
     */
    public List<Product> getHotProducts(int limit) {
        try {
            return productMapper.selectHotProducts(limit);
        } catch (Exception e) {
            log.error("查询热销商品失败", e);
            throw new RuntimeException("查询热销商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取新品商品
     */
    public List<Product> getNewProducts(int limit) {
        try {
            return productMapper.selectNewProducts(limit);
        } catch (Exception e) {
            log.error("查询新品商品失败", e);
            throw new RuntimeException("查询新品商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取库存不足商品
     */
    public List<Product> getLowStockProducts() {
        try {
            return productMapper.selectLowStockProducts();
        } catch (Exception e) {
            log.error("查询库存不足商品失败", e);
            throw new RuntimeException("查询库存不足商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取统计信息
     */
    public Map<String, Object> getStatistics() {
        try {
            Map<String, Object> stats = productMapper.getStatistics();
            List<Map<String, Object>> categoryStats = productMapper.countByCategory();
            stats.put("categoryStats", categoryStats);
            return stats;
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            throw new RuntimeException("获取统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有分类ID
     */
    public List<String> getAllCategoryIds() {
        try {
            return productMapper.selectAllCategoryIds();
        } catch (Exception e) {
            log.error("获取所有分类ID失败", e);
            throw new RuntimeException("获取所有分类ID失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取推荐商品（首页展示）
     */
    public List<Product> getRecommendedProducts(int limit) {
        try {
            return productMapper.selectRecommendedProducts(limit);
        } catch (Exception e) {
            log.error("查询推荐商品失败", e);
            throw new RuntimeException("查询推荐商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取商品搜索建议
     */
    public List<String> getProductSuggestions(String keyword, int limit) {
        try {
            return productMapper.selectProductSuggestions(keyword, limit);
        } catch (Exception e) {
            log.error("获取商品搜索建议失败", e);
            throw new RuntimeException("获取商品搜索建议失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取促销商品
     */
    public List<Product> getPromotionProducts(int limit) {
        try {
            return productMapper.selectPromotionProducts(limit);
        } catch (Exception e) {
            log.error("查询促销商品失败", e);
            throw new RuntimeException("查询促销商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取相关商品（基于商品分类）
     */
    public List<Product> getRelatedProducts(String categoryId, String excludeProductId, int limit) {
        try {
            return productMapper.selectRelatedProducts(categoryId, excludeProductId, limit);
        } catch (Exception e) {
            log.error("查询相关商品失败", e);
            throw new RuntimeException("查询相关商品失败: " + e.getMessage());
        }
    }
}